<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoles } from '@/api/setting'
import { reqGetUserDetailById, reqAssignRoles } from '@/api/employee'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleIds: [],
      roleList: [],
      loading: false
    }
  },

  methods: {
    handleClose() {
      this.$emit('update:showRoleDialog', false)
      this.roleIds = []
    },

    handleOpen() {
      this.loading = true
      // 以下的两个方法用ajax 异步的
      // this.getRoleList()
      // this.getEmployeeRole()

      // 需求: 当两个ajax请求全部加载数据完成时,loading = false
      // Promise                 all()    race()   reject()  resolve()
      // p = new Promise()       then()   catch()  finally()
      // Promise.all([p实例1,p实例2...]).then()

      Promise.all([this.getRoleList(), this.getEmployeeRole()]).then(() => {
        this.loading = false
      })
    },

    // 获取所有的角色列表数据
    async getRoleList() {
      const { data: { rows }} = await reqGetRoles(1, 9999)
      this.roleList = rows
    },

    // 获取员工已有的角色
    async getEmployeeRole() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      this.roleIds = roleIds
    },

    // 重新提交角色
    async clickSubmit() {
      await reqAssignRoles(this.userId, this.roleIds)
      this.$message.success('分配角色成功')
      this.handleClose()
    }
  }
}
</script>

<style scoped lang=''>

</style>
